package com.zjw.concurrency.aqs;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreExample {

    //每次线程池里只允许三个线程执行
    static Semaphore semaphore = new Semaphore(3,true);

    public static void main(String[] args) {


        //新建coreSize容量为50的线程池，
        ExecutorService executorService = Executors.newFixedThreadPool(50);
        for (int i = 0; i < 100; i++) {

            Task task = new Task();
            executorService.submit(task);
        }
        executorService.shutdown();
    }

    static class Task implements Runnable{

        @Override
        public void run() {
            try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName() + "线程已经拿到许可");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                System.out.println(Thread.currentThread().getName() + "释放了许可证");
                semaphore.release();
            }
        }
    }
}


